{extend name="main"}
{block name="style"}
<style>
    .hide .el-upload--picture-card {
        display: none;
    }
</style>
{/block}
{block name="body"}


<el-drawer
        title="选择标签"
        :visible.sync="tagsDrawer"
        :before-close="handleClose">
    <el-card class="box-card my-3" v-for="(v,i) in tableData">
        <div slot="header" class="clearfix">
            <span>{{v.name}}</span>
        </div>
<!--        <el-tag  v-for="vo in v.tags" :key="vo.id" class="m-2" v-if="vo.name!=''">{{vo.name}}</el-tag>-->
            <el-checkbox-group v-model="checkboxGroup"size="mini" @change="getValue()">
                <el-checkbox  v-for="vo in v.tags" :key="vo.id" v-if="vo.name!=''" :label="vo.id"   border class="my-2">{{vo.name}}</el-checkbox>
            </el-checkbox-group>

        <el-input  placeholder="回车键保存"
                v-model="addTagInput"
                  maxlength="15"
                  type="text"
                  size="small"
                  show-word-limit
                  style="width:200px;"
                  @keyup.enter.native="addTag(event,v)"
                  v-if="showAddTag&&addIndex==i"
                  v-focus ></el-input>
        <el-button plain size="mini" icon="el-icon-plus" @click="addTagShow(i)">添加标签</el-button>
    </el-card>
</el-drawer>

<div class="bg-white p-3">

    <el-form ref="form" :model="form" :rules="rules" label-width="120px"  v-loading="form.ajax">
        <el-form-item label="二维码名称"  prop="title">
            <el-input v-model="form.title"  size="small" style="width: 40%" placeholder="名称不会展示给用户，用于企业记录渠道或使用场景"></el-input>
        </el-form-item>
        <el-form-item label="所属分组" prop="pid">
            <el-select v-model="form.pid" placeholder="请选择" size="small" style="width: 40%">
                <el-option
                        v-for="item in groupData"
                        :key="item.id"
                        :label="item.title"
                        :value="item.id">
                </el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="添加员工" prop="userValue">
            <el-select v-model="form.userValue" multiple placeholder="请选择" style="width: 40%"    size="small">
                <el-option
                        v-for="item in user"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                </el-option>
            </el-select>
        </el-form-item>
        <el-form-item  label="客户标签">
            <el-switch
                    v-model="form.tags"
                    active-color="#13ce66"
                    >
            </el-switch>
            <span v-if="form.tags">已开启</span>
            <span v-else>已关闭</span>
            <el-button size="mini" v-if="form.tags" @click="openAndGetTag"><i class="el-icon-plus" ></i>添加标签</el-button>
        </el-form-item>
        <el-form-item v-if="form.tags">
            <el-tag
                    v-for="tag in form.checkTagGroup"
                    :key="tag.id"
                    closable
                    @close="closeTags(tag.id)"
                    type="success"
                    class="m-1"
                    effect="dark">
                {{tag.name}}
            </el-tag>
        </el-form-item>
        <el-form-item  label="自动通过好友">
            <el-switch
                    v-model="form.skip_verify"
                    active-color="#13ce66"
            @change="skipVerifyChang">
            </el-switch>
            <span v-if="form.skip_verify">已开启</span>
            <span v-else>已关闭</span>
        </el-form-item>
        <el-form-item  label="开启时间" v-if="form.showAutoSkip">
            <el-radio-group v-model="form.auto_skip">
                <el-radio :label="0">关闭</el-radio>
                <el-radio :label="1">开启</el-radio>
            </el-radio-group>
            <div v-if="form.auto_skip==1">
                <el-time-picker
                        size="small"
                        v-model="form.valida_start_time"
                        type="date"
                        format="HH:mm:ss"
                        value-format="HH:mm:ss"
                        placeholder="请输入开始时间">
                </el-time-picker>
                至
                <el-time-picker
                        size="small"
                        v-model="form.valida_end_time"
                        type="date"
                        format="HH:mm:ss"
                        value-format="HH:mm:ss"
                        placeholder="请输入结束时间">
                </el-time-picker>
            </div>
            <div style="color: #9DA9B6">在非开启【自动通过好友】时间段添加的好友，需要客服手动通过好友验证才可添加</div>
        </el-form-item>
        <div  style="background-color:#FFF6F7;border-radius: 0px;color: #B5692D;margin-bottom: 5px; border-left:5px solid #fe6c6f">
            <div style="flex: 1 1 0%;padding: 15px">
                <span><i class="el-icon-warning" style="color: rgb(250, 173, 20); margin-right: 5px;"></i> 因企业微信限制，若使用成员已在<strong>【企业微信后台】</strong>配置了欢迎语，这里的欢迎语将不会生效。</span>
            </div>
        </div>
        <el-form-item label="设置欢迎语">
            <el-radio-group v-model="form.send_welcome">
                <el-radio :label="1">渠道欢迎语</el-radio>
                <el-radio :label="2">默认欢迎语</el-radio>
                <el-radio :label="3">不发送欢迎语</el-radio>
            </el-radio-group>
            <div v-if="form.send_welcome==2" style="color: #9DA9B6">将发送员工成员已设置的好友欢迎语，若所选成员未设置好友欢迎语，则不会发送内容</div>
        </el-form-item>
<div v-if="form.send_welcome==1">
        <el-form-item label="欢迎语1">
            <el-input style="width: 40%"    size="small"
                      type="textarea"
                      :rows="4"
                      maxlength="600"
                      show-word-limit
                      placeholder="请输入欢迎语1"
                      v-model="form.content">
            </el-input>
            <el-button type="text" @click="addCustomerName">[插入客户昵称]</el-button>
        </el-form-item>


        <el-form-item label="欢迎语2">
            <el-radio-group v-model="form.content_type">
                <el-radio  :label="1">图片</el-radio>
                <el-radio :label="2">链接</el-radio>
                <el-radio :label="3">小程序</el-radio>
            </el-radio-group>


            <div v-if="form.content_type==1">
                <el-upload
                        name="file"
                        action="/work-wechat/uploadimgToWeChat"
                        :data="{path:'web/img'}"
                        list-type="picture-card"
                        :on-preview="handlePictureCardPreview"
                        :on-remove="handleRemove"
                        :on-success="handleAvatarSuccess"
                        :on-error="handleAvatarError"
                        :file-list="picArr"
                        :class="{hide:hideUpload}">
                    <i class="el-icon-plus"></i>
                </el-upload>
                <el-dialog :visible.sync="dialogVisible">
                    <img width="100%" :src="form.itemData.image.pic_url" alt="">
                </el-dialog>
            </div>
            <div v-else-if="form.content_type==2" >
                <el-form-item label="链接" class="my-2" >
                    <el-input v-model="form.itemData.link.url"  size="small" style="width: 35%" placeholder="链接地址请以http或https开头"></el-input>
                </el-form-item>
                <el-form-item label="标题" class="my-2" >
                    <el-input v-model="form.itemData.link.title"  size="small" style="width: 35%" placeholder="请输入链接标题"></el-input>
                </el-form-item>
                <el-form-item label="描述" class="my-2" >
                    <el-input v-model="form.itemData.link.desc"  size="small" style="width: 35%" placeholder="请输入链接描述"></el-input>
                </el-form-item>
                <el-form-item label="封面图片">
                    <el-upload
                            name="file"
                            action="/work-wechat/uploadimgToWeChat"
                            list-type="picture-card"
                            :on-preview="handlePictureCardPreview"
                            :on-remove="handleRemove"
                            :on-success="handleAvatarSuccess"
                            :on-error="handleAvatarError"
                            :file-list="picArr"
                            :class="{hide:hideUpload}">
                        <i class="el-icon-plus"></i>
                    </el-upload>
                    <el-dialog :visible.sync="dialogVisible">
                        <img width="100%" :src="form.itemData.link.picurl" alt="">
                    </el-dialog>
                </el-form-item>
            </div>
            <div v-else-if="form.content_type==3">
                <span style="color:red;">该小程序必须是关联到企业的小程序应用，否则将会推送失败</span>
                <el-form-item label="标题" class="my-2" >
                    <el-input v-model="form.itemData.miniprogram.title"  size="small" style="width: 35%" placeholder="请输入小程序标题"></el-input>
                </el-form-item>
                <el-form-item label="小程序appid"class="my-2" >
                    <el-input v-model="form.itemData.miniprogram.appid"  size="small" style="width: 35%" placeholder="请输入小程序appid"></el-input>
                </el-form-item>
                <el-form-item label="小程序路径" class="my-2" >
                    <el-input v-model="form.itemData.miniprogram.page"  size="small" style="width: 35%" placeholder="请输入小程序路径"></el-input>
                </el-form-item>
                <el-form-item label="封面图片">
                    <el-upload
                            action="/uploadFiles"
                            :data="{path:'web/img'}"
                            list-type="picture-card"
                            :on-success="handleAvatarSuccess"
                            :on-error="handleAvatarError"
                            :on-preview="handlePictureCardPreview"
                            :on-remove="handleRemove"
                            :file-list="picArr"
                            :class="{hide:hideUpload}">
                        <i class="el-icon-plus"></i>
                    </el-upload>
                    <el-dialog :visible.sync="dialogVisible">
                        <img width="100%" :src="form.itemData.miniprogram.picurl" alt="">
                    </el-dialog>
                </el-form-item>
            </div>
        </el-form-item>

        <div  style="background-color:#F9FAFC;box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);color: #5e6d82;margin-bottom: 50px;">
            <div style="flex: 1 1 0%;padding: 20px">
                注意:
                <ul>
                    <li>
                        <span>1、新建欢迎语最多可发送1条文字消息和1种图片/外链/小程序类型的消息</span>
                    </li>
                    <li>
                        <span>2、欢迎语1和2不能同时为空，当两者均填写时用户会收到两条消息</span>
                    </li>
                    <li>
                        <span>3、欢迎语将在客户加为好友后20秒内下发，因网络延迟可能造成发送不成功</span>
                    </li>
                </ul>
            </div>
        </div>
</div>
        <el-form-item>
            <el-button type="primary" @click="onSubmit">立即保存</el-button>
            <el-button  @click="()=>{window.location.href='/work-wechat/channelCode';}">取消</el-button>
        </el-form-item>
    </el-form>

</div>
{/block}
{block name="script"}
<script type="text/javascript">
    var groupData = JSON.parse('{:json_encode($groupData)}'.replace(/[\r\n\s+]/g, '\\n'));
    var groupDataValue=groupData[0].id;
    var user = JSON.parse('{:json_encode($user)}'.replace(/[\r\n\s+]/g, '\\n'));
    var title=''
    var content=''
    var content_type=1
    var send_welcome=1
    var tags=false
    var checkTagGroup=[]
    var checkboxGroup=[]
    var auto_skip=0
    var valida_start_time=''
    var valida_end_time=''
    var appid="{$appid}";
    var itemData={
        image:{
            pic_url:'',
        },
        link:{
            url:'',
            title:'',
            desc:'',
            picurl:""
        },
        miniprogram:{
            title:'',
            appid:appid,
            page:'/pages/common/home/home',
            path:'',
            picurl:""
        }
    }
    var picArr=[]

    {empty name="channelCode"}
    var is_edit=false;
    var dialogVisible=false;
    var hideUpload=false;
    var url='/work-wechat/addChannelCode';
    var userValue=[];
    {else/}
        var is_edit=true;
        var dialogVisible=false;
        var hideUpload=false;
        var url='/work-wechat/modifyChannelCode/{$channelCode.id}';
        var userValue=JSON.parse('{:json_encode($selectUser)}');
        var us=[]
        userValue.filter(function (item){
             us.push(parseInt(item))
        })
        userValue=us;
        var channelCode= {$channelCode|raw};
        var welcome=JSON.parse(channelCode.welcome_text)
        send_welcome=channelCode.send_welcome
        tags=channelCode.tags_type==1?true:false;
        checkTagGroup=JSON.parse(channelCode.tags)
        if (checkTagGroup!=null){
            checkTagGroup.filter(function (item){
                checkboxGroup.push(parseInt(item.id));
            })
        }
        auto_skip=channelCode.auto_skip
        valida_start_time=channelCode.valida_start_time;
        valida_end_time=channelCode.valida_end_time;

        if (send_welcome==1){
            var itemDa=welcome.itemData
            let urls="";
            content_type=parseInt(welcome.content_type)
            switch (content_type){
                case 1:itemData.image=itemDa;
                    urls=itemData.image.pic_url;
                    break;
                case 2:itemData.link=itemDa;
                    urls=itemData.link.picurl;
                    break;
                case 3:itemData.miniprogram=itemDa;
                    urls=itemData.miniprogram.picurl;
                    break;
            }
            if (urls != ''){
                picArr.push({
                    url:urls
                })
                var hideUpload=true;
            }
            content=welcome.content;
        }
        title=channelCode.title;
        {/empty}
</script>
<script type="text/javascript">
    var vm = new Vue({
        el: '#app',
        data: {
            view: XYBase.view,
            hideUpload: hideUpload,
            limitCount:1,
            groupData:groupData,
            tagsDrawer:false,
            tableData: [],
            //选中标签
            checkboxGroup:checkboxGroup,
            showAddTag:false,
            addTagInput:'',
            picArr:picArr,
            form: {
                //标题
                title:title,
                //所属分组
                pid:groupDataValue,
                ajax:false,
                //是否启用标签
                tags:tags,
                //选择后在页面展示的标签列表
                checkTagGroup:checkTagGroup,
                //是否跳过好友验证，默认是
                skip_verify:true,
                showAutoSkip:true,
                auto_skip:auto_skip,
                valida_start_time:valida_start_time,
                valida_end_time:valida_end_time,
                //是否发送好友欢迎语，1=>创建活码是添加的，2=>在好友欢迎语中设置的，3=>不发送
                send_welcome:send_welcome,
                userValue:userValue,
                content:content,
                content_type:content_type,
                itemData:itemData
            },
            user:user,
            dialogVisible: dialogVisible,
            rules: {
                title: [
                    { required: true, message: ' 请输入欢迎语名称', trigger: 'blur' },
                ],
                pid:[
                    { required: true, message: '所属分组不能为空，请选择或添加分组后新建', trigger: 'blur' },
                ],
                userValue:[
                    { required: true, message: '请选择员工', trigger: 'blur' },
                ]
            }
        },
        watch: {
            view: XYBase.viewWatch,
        },
        created() {
            XYBase.created(this);
        },
        methods: {
            //提交创建
            onSubmit() {
                var _this=this;
                let itemData='';
                if (_this.form.title==''){
                    XYBase.error("请输入二维码名称");
                    return;
                }
                if (_this.form.pid==undefined || _this.form.pid==''){
                        XYBase.error("请选择所属分组")
                        return;
                }
                if(_this.form.userValue.length<1){
                    XYBase.error("请选择员工")
                    return;
                }
                let oldItemData=_this.form;
                if (_this.form.send_welcome==1) {
                    if (_this.form.content_type == 2) {
                        if (_this.checkItemData(_this.form.itemData.link) && _this.form.content == '') {
                            XYBase.error("请完善欢迎语2的外链表单");
                            return;
                        }
                        itemData = _this.form.itemData.link;
                    } else if (_this.form.content_type == 3) {
                        if (_this.checkItemData(_this.form.itemData.miniprogram) && _this.form.content == '') {
                            XYBase.error("请完善欢迎语2的小程序的表单");
                            return;
                        }
                        itemData = _this.form.itemData.miniprogram;
                    } else {
                        if (_this.checkItemData(_this.form.itemData.image) && _this.form.content == '') {
                            XYBase.error("请上传欢迎语2的图片");
                            return;
                        }
                        itemData = _this.form.itemData.image;
                    }
                    oldItemData.itemData = itemData
                    oldItemData = {...oldItemData}
                }

                _this.form.ajax=true;
                _this.setFormItem(_this.form)
                $.ajax({
                    url:url,
                    // url:"/work-wechat/addChannelCode",
                    type:'post',
                    data:oldItemData,
                    dataType:'json',
                    error:function(err){
                        _this.form.ajax=false;
                        XYBase.error(XYBase.config.system_network_error);
                    },
                    success:function(ret){
                        _this.form.ajax=false;
                        if (ret) {
                            if (ret.code === 0) {
                                XYBase.success("保存成功");
                                setTimeout(() => {
                                    window.location.href='/work-wechat/channelCode';
                                }, 1000);
                            }else{
                                XYBase.msg(ret.msg);
                            }
                        }else{
                            XYBase.error(XYBase.config.system_network_error);
                        }
                    }
                });
            },
            setFormItem(data){
                var itemData={
                    image:{
                        pic_url:'',
                    },
                    link:{
                        url:'',
                        title:'',
                        desc:'',
                        picurl:""
                    },
                    miniprogram:{
                        title:'',
                        appid:'',
                        page:'',
                        path:'',
                        picurl:''

                    }
                }
                switch (data.content_type){
                    case 1:itemData.image=data.itemData;
                        urls=itemData.image.pic_url;
                        break;
                    case 2:itemData.link=data.itemData;
                        urls=itemData.link.picurl;
                        break;
                    case 3:itemData.miniprogram=data.itemData;
                        urls=itemData.miniprogram.picurl;
                        break;
                }
                this.form.itemData=itemData;
            },
            checkItemData(obj){
                for (var key in obj){
                    if (obj.hasOwnProperty(key) && key !='picurl') {
                        if (obj[key] === null || obj[key] === '') {
                            return true;
                        }
                    }
                }
                return false;
            },
            skipVerifyChang(value){
                // console.log(value)
                this.form.showAutoSkip=value;
            },
            handleAvatarSuccess:function(res, file) {
                if(res){
                    if(res.code === 0){
                        if(this.form.content_type==2)
                            this.form.itemData.link.picurl=res.data;
                        else if(this.form.content_type==3){
                            this.form.itemData.miniprogram.picurl=res.data.url;
                            this.form.itemData.miniprogram.path=res.data.path;
                    }
                        else
                            this.form.itemData.image.pic_url=res.data;
                        this.hideUpload = true;
                        XYBase.success(res.msg);
                    }else{XYBase.error(res.msg);}
                }else{XYBase.error(XYBase.config.system_network_error)}
            },
            handleAvatarError:function(res, file) {
                XYBase.error(XYBase.config.system_network_error)
            },

            //点击添加客户昵称
            addCustomerName(){
                this.form.content+='#用户昵称#'
            },

            handleRemove(file, fileList) {
                // console.log(file, fileList);
                this.hideUpload=false;

            },
            //点击图片上传
            handlePictureCardPreview(file) {
                // this.dialogImageUrl = file.url;
                this.dialogVisible = true;
            },
            openAndGetTag(){
                this.getTagsList();
                this.tagsDrawer=true;
            },
            //点击添加标签按钮
            addTagShow(index){
                // this.showAddTag=!this.showAddTag
                this.showAddTag = true
                this.addIndex = index
            },
            //关闭选择标签的弹窗
            handleClose(done){

                if (this.checkboxGroup.length<1){
                    this.$confirm('未选择标签,是否关闭？')
                        .then(_ => {
                            this.form.tags=false;
                            done();
                        })
                        .catch(_ => {});
                }else {
                    done();
                }
            },
            //获取标签信息
            getTagsList(){
                let _this=this;
                $.ajax({
                    url: '/work-wechat/customerLabel',
                    data: _this.search,
                    type:'post',
                    dataType:'json',
                    success(res) {
                        if (res.code != undefined && res.code == 0) {
                            _this.tableData = res.data
                            if (_this.tableData.length < 1) {
                                XYBase.msg('暂无数据~')
                            } else {
                                // XYBase.success('获取成功')
                            }
                        } else if (res.msg != undefined) {
                            XYBase.msg(res.msg)
                        }
                    },
                    error(xhr) {
                        XYBase.error(XYBase.config.system_network_error)
                        // console.log(xhr)
                    }
                })
            },
            //选中标签的方法
            getValue(){
                let souceData=[];
                this.form.checkTagGroup=[];
                this.tableData.map((item)=>{
                    souceData=souceData.concat(item.tags)
                })
                souceData.map((item)=>{
                    this.checkboxGroup.map((group)=>{
                        if (item.id==group){
                            this.form.checkTagGroup.push(item)
                        }
                    })
                })
             },
            //点击关闭标签
            closeTags(tag){
                this.checkboxGroup.splice(this.checkboxGroup.indexOf(tag), 1);
                var newData = this.form.checkTagGroup.filter(function(item) {
                    return item.id != tag;
                });
                this.form.checkTagGroup=newData;
            },
            //添加标签的方法
            addTag(event,group){
                let value=event.target.value;
                if (value=="" || value==undefined || value.length<1){
                    this.showAddTag=!this.showAddTag
                    this.input='';
                    return;
                }
                let _this = this
                $.ajax({
                    url:'/work-wechat/addTagForTagGroup',
                    type: 'post',
                    data:{name:event.target.value,group_id:group.group_id,tagGroupId:group.id},
                    dataType: 'json',
                    success(res) {
                        if (res.code != undefined && res.code == 0) {
                            _this.tableData = res.data
                            _this.showAddTag=false
                            _this.addTagInput='';
                            XYBase.success('添加成功')
                        } else if (res.msg != undefined) {
                            XYBase.msg(res.msg)
                        }
                    },
                    error(xhr) {
                        XYBase.error(XYBase.config.system_network_error)
                        // console.log(xhr)
                    },
                });
            },



        }
    });
    $(function () {
        $(window).resize(function () {
            reloadWindowSize();
        });
    });
    function reloadWindowSize(argument) {
        var winW = $(window).width();
        if (winW <= 576) {
            vm.labelPosition = 'top';
        } else {
            vm.labelPosition = 'right';
        }
    }
</script>
{/block}